#include "SmsCodeTask.h"

SmsCodeTask::SmsCodeTask(char* body, int client_fd, int len, int shmid, int msgid):BaseTask(body,client_fd,len, shmid,msgid)
{
}

string SmsCodeTask::VerifyCode()
{
	std::string code;
	srand(time(nullptr)); // 初始化随机数种子

	for (int i = 0; i < 6; ++i)
	{
		int digit = rand() % 10; // 生成 0-9 的随机数字
		code += std::to_string(digit); // 将数字转换为字符串并追加到 code
	}
	return code;
}

ssize_t http_post(char* page, char* poststr, int basefd)
{
    char sendline[MAXLINE + 1], recvline[MAXLINE + 1];
    ssize_t n;
    snprintf(sendline, MAXSUB,
        "POST %s HTTP/1.0\r\n"
        "Host: %s\r\n"
        "Content-type: application/x-www-form-urlencoded\r\n"
        "Content-length: %zu\r\n\r\n"
        "%s", page, "106.ihuyi.cn", strlen(poststr), poststr);

    write(basefd, sendline, strlen(sendline));
    while ((n = read(basefd, recvline, MAXLINE)) > 0) {
        recvline[n] = '\0';
        printf("%s", recvline);
    }
    return n;
}

/**
* 发送短信
*/
ssize_t send_sms(char* account, char* password, char* mobile, char* content,int basefd)
{
    char params[MAXPARAM + 1];
    char* cp = params;
    sprintf(cp, "account=%s&password=%s&mobile=%s&content=%s", account, password, mobile, content);
    return http_post("/webservice/sms.php?method=Submit&format=json", cp, basefd);
}

int socked_connect(char* arg)
{
    struct sockaddr_in their_addr = { 0 };
    char buf[1024] = { 0 };
    char rbuf[1024] = { 0 };
    char pass[128] = { 0 };
    struct hostent* host = NULL;

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        printf("create the sockfd is failed\n");
        return -1;
    }

    if ((host = gethostbyname(arg)) == NULL)
    {
        printf("Gethostname error, %s\n");
        return -1;
    }

    memset(&their_addr, 0, sizeof(their_addr));
    their_addr.sin_family = AF_INET;
    their_addr.sin_port = htons(80);
    their_addr.sin_addr = *((struct in_addr*)host->h_addr);
    if (connect(sockfd, (struct sockaddr*)&their_addr, sizeof(struct sockaddr)) < 0)
    {
        close(sockfd);
        return  -1;
    }
    printf("connect is success\n");
    return sockfd;

}


void SmsCodeTask::SendCode(string &phone)
{
    struct sockaddr_in servaddr;
    char str[50];

    int basefd;
    if ((basefd = socked_connect("106.ihuyi.cn")) == -1)
    {
        printf("connect is failed\n");
    }
    printf("basefd is =%d\n", basefd);
    //用户名是登录用户中心->验证码短信->产品总览->APIID
    char* account = "C21244969";

    //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
    //char* password = "bc207cb3b3541fe2a6a92ff2c7f66b05";
    char* password = "7d76324f4174cb4dd510352e2ccece9e";
    //手机号
    char* mobile = (char *)phone.c_str();
    int phoneNumber = atoi(phone.c_str());
    //短信内容
    string code = Codemap[phoneNumber];
    string message = "您的验证码是：" + code + "。请不要把验证码泄露给其他人。";

    // 将 std::string 转换为 char*
    char* charMessage = new char[message.size() + 1]; // 分配内存
    strcpy(charMessage, message.c_str()); // 复制内容

    cout <<"messsge=====" << charMessage << endl;



    /**************** 发送短信 *****************/
    send_sms(account, password, mobile, charMessage, basefd);
    printf("send the message is success\n");
    close(basefd);    
    // 使用完毕后释放内存
    delete[] charMessage;
}


void SmsCodeTask::working()
{
    cout << "------发送手机验证码中................" << endl;
    ShmControl* shm = (ShmControl*)shmat(shmid, NULL, 0);
    int index = -1;//空闲下标
    // 寻找下一个空闲块（状态0）
    for (int i = 0; i < MEMORYNUMBER; i++) {
        int status = shm->blocks[i].status;
        if (status == 0) { // 空闲
            index = i;
            break;
        }
    }
	SMS_CODE_REQ sms_code_req = { 0 }; //请求头
	RESP resp = { 0 };//响应结构体
	char date[MEMORYSIZE] = { 0 };
	//写头
    HEAD head = { 0 };
	head.data_len = sizeof(RESP);
    head.index = 1;
	head.service_type = SMS_CODE;
	head.checksum = 100;
	//拿到请求信息
	memcpy(&sms_code_req, body,sizeof(SMS_CODE_REQ));
    string phone =  sms_code_req.phone_number;
	std::string str1("");
	shared_ptr<User> user = model->getUser(str1, phone);
    if (user==nullptr)//检验手机号是否已经被绑定
    {
	    //获取随机验证码
	    Codemap[atoi(sms_code_req.phone_number)]= VerifyCode();//存入验证码
		
	    SendCode(phone);//发送验证码
	    cout << "code=" << Codemap[atoi(sms_code_req.phone_number)] <<endl;
	    //写体
	    strcpy(resp.message, "发送手机验证码：发送成功！");
	    resp.status_code = Success;
    }
    else
    {
        cout << "发送手机验证码：手机号已存在"<< endl;
        //写体
        strcpy(resp.message, "发送手机验证码：手机号已存在！");
        resp.status_code = Failure;
    }	   
    //头体结合
	memcpy(date, &head, sizeof(HEAD));
	memcpy(date + sizeof(HEAD), &resp, sizeof(RESP));
    sem_p(sem_shm, 0);//获取共享内存锁
    //写入共享内存
    ShmBlock* block = &shm->blocks[index];
    memcpy(block->data, date, sizeof(block->data));//考入共享内存
    block->status = 1;                   // 标记为已写
    shmdt(shm);
    sem_v(sem_shm, 0);//获取共享内存锁
	//写入消息队列
	MSG msg = { 0 };
	msg.client_fd = client_fd;
	msg.index = index;
	msg.mtype = 1;
	msgsnd(msgid, &msg,sizeof(MSG),0);
	cout << "---------验证码已发送给=" << client_fd << endl;
}
